import React, {
  useImperativeHandle,
  //useRef,
  forwardRef,
  useState,
} from 'react';
import { Dimensions, Platform, Text, StyleSheet } from 'react-native';
import {
  InputItem,
  Modal,
  List,
  Toast,
  Flex,
  ActivityIndicator,
} from '@ant-design/react-native';
import dayjs from 'dayjs';
import { formatDate } from '@/helpers/dateutil';
import UserStore from '@/stores/userStore';
import PhotoCameraPicker from '@/rcomponents/photoCameraPicker';
import MaintainJobStore from '../maintainJobStore';
import RadioButtonGroup from '@/rcomponents/radioButtonGroup';

const dimWidth = Dimensions.get('window').width;

const styles = StyleSheet.create({
  closeBtn: { padding: 10 },
  manHourInput: {
    borderWidth: 1,
    marginRight: 5,
    borderColor: '#ddd',
  },
  departInput: {
    borderLeftWidth: 1,
    borderRightWidth: 1,
    borderColor: '#ddd',
  },
  modalPosition: {
    position: 'relative',
    bottom: Platform.isPad ? 200 : 0,
  },
});

function MaintainJobClose({ onSubmit, fromSign }, ref) {
  const [visible, setVisible] = useState(false);
  const [confirming, setConfirming] = useState(false);
  const userStore = UserStore.useStore();
  const mjStore = MaintainJobStore.useStore();
  const [jobTask, setJobTask] = useState();
  const [filterOpt, setFilterOpt] = useState('');
  const [jobcloseForm, setJobCloseForm] = useState({
    inspector: '',
    man: '',
    hours: '',
    depart: '长龙航空',
    filePath: '',
    taskFeedback: '',
    flbNo: '',
  });
  useImperativeHandle(ref, () => ({
    show: (jTask) => {
      setJobTask({ ...jTask, finishDate: dayjs() });
      handleModal();
    },
    hide: handleModal,
  }));
  const handleSubmit = async () => {
    jobTask.orderType === 'MCO_C' && !filterOpt.length
      ? Toast.fail('请选择是否关闭保留')
      : '';
    jobTask.orderType === 'MCO_P' && !filterOpt.length
      ? Toast.fail('请选择是否关闭缺件清单')
      : '';
    if (confirming) {
      return;
    }
    if (fromSign) {
      setConfirming(true);
      let confirmRes = true;
      if (onSubmit) {
        confirmRes = await onSubmit(true);
      }
      setConfirming(false);
      if (!confirmRes) {
        return;
      }
    }
    const jobCloseData = {
      tid: jobTask.id,
      wkOrder: jobTask.workOrder,
      orderType: jobTask.orderType,
      jcNo: jobTask.jobCard,
      acno: jobTask.acno,
      exePerson: userStore.user.Name,
      whStart: jobcloseForm.man,
      whEnd: jobcloseForm.hours,
      itemNo: jobTask.itemNo,
      exDate: formatDate(jobTask && jobTask.finishDate, 'YYYY/MM/DD HH:mm:ss'), //执行日期
      filePath: jobcloseForm.filePath,
      station: jobTask.airport,
      depart: jobcloseForm.depart,
    };
    const mcoClosePara = {
      checker: jobcloseForm.inspector, //检查者
      feedmemo: jobcloseForm.taskFeedback, //工作内容反馈
      flbNO: jobcloseForm.flbNo,
      accomplishedBy: userStore.user.Name, //完工签署
      mco_c: '2',
      ifCLoseDDFC: jobTask.orderType === 'MCO_C' ? filterOpt : '2',
      ifCLosePMP: jobTask.orderType === 'MCO_p' ? filterOpt : '2',
    };
    //非MCO关闭
    if (jobTask.workOrder.substring(0, 3) !== 'MCO') {
      const res = await mjStore.closePlanJob(
        userStore.user.LoginName,
        Object.assign(jobCloseData),
      );
      if (!res.errorCode) {
        handleModal();
        onSubmit();
      } else {
        Toast.fail(res.errorMsg);
      }
    } else if (jobTask.orderType === 'MCO_C' || jobTask.orderType === 'MCO_P') {
      // MCO 选择-关闭保留
      if (filterOpt === '2') {
        const res = await mjStore.closePackCloseDfc(
          userStore.user.LoginName,
          Object.assign(jobCloseData, mcoClosePara),
        );

        if (!res.errorCode) {
          handleModal();
          onSubmit();
        } else {
          Toast.fail(res.errorMsg);
        }
      } else {
        // MCO 选择-不关闭保留
        const res = await mjStore.closePackNotCloseDfc(
          userStore.user.LoginName,
          Object.assign(jobCloseData, mcoClosePara),
        );
        if (!res.errorCode) {
          handleModal();
          onSubmit();
        } else {
          Toast.fail(res.errorMsg);
        }
      }
    } else {
      // MCO 不选择
      console.log(Object.assign(jobCloseData, mcoClosePara));
      console.log(typeof mcoClosePara.ActMH);
      const res = await mjStore.closePackOfMco(
        userStore.user.LoginName,
        Object.assign(jobCloseData, mcoClosePara),
      );
      if (!res.errorCode) {
        handleModal();
        onSubmit();
      } else {
        Toast.fail(res.errorMsg);
      }
    }
  };
  const handleModal = () => {
    setVisible(!visible);
    Object.keys(jobcloseForm).forEach((key) => {
      jobcloseForm[key] = '';
      jobcloseForm.depart = '长龙航空';
    });
  };
  const isCloseNull = Object.values(jobcloseForm).filter((item) => item === '')
    .length;
  const isSignNull = jobcloseForm.man !== '' && jobcloseForm.hours !== '';
  return (
    <Modal
      transparent
      animationType="slide-up"
      visible={visible}
      style={[
        { width: dimWidth * (Platform.isPad ? 2 / 3 : 11 / 12) },
        styles.modalPosition,
      ]}
      title="关闭任务"
      footer={[
        {
          text: '取消',
          onPress: handleModal,
        },
        {
          text: (
            <>
              <ActivityIndicator animating={confirming} />
              <Text>
                {fromSign
                  ? isSignNull
                    ? '签字'
                    : '未填写不可签字'
                  : !isCloseNull
                  ? '提交'
                  : '未填写不可提交'}
              </Text>
            </>
          ),
          onPress: isSignNull || isCloseNull ? handleSubmit : '',
        },
      ]}
    >
      <List>
        <InputItem editable={false} value={userStore.user.Name}>
          工作者
        </InputItem>

        <Flex>
          <Flex.Item flex={6}>
            <InputItem
              value={jobcloseForm.man}
              style={styles.manHourInput}
              onChange={(val) => {
                //输入内容只能为数字型（空格、非数字清除，首位为“.”、“0”清除，多个“."清除）
                let newVal = val !== '' && val.substr(0, 1) === '.' ? '' : val;
                newVal = newVal.replace(/^0/g, '');
                newVal = newVal.replace(/[^\d.]/g, '');
                newVal = newVal.replace(/\.{2,}/g, '');
                newVal = newVal
                  .replace('.', '$#$')
                  .replace(/\./g, '')
                  .replace('$#$', '.');
                setJobCloseForm({ ...jobcloseForm, man: newVal });
              }}
              extra={<Text>人</Text>}
            >
              完工工时
            </InputItem>
          </Flex.Item>
          <Text> X </Text>
          <Flex.Item flex={4}>
            <InputItem
              value={jobcloseForm.hours}
              style={styles.manHourInput}
              onChange={(val) => {
                let newVal = val !== '' && val.substr(0, 1) === '.' ? '' : val;
                // newVal = newVal.replace(/^0{0,1}/g);
                newVal = newVal.replace(/[^\d.]/g, '');
                newVal = newVal.replace(/\.{2,}/g, '');
                newVal = newVal
                  .replace('.', '$#$')
                  .replace(/\./g, '')
                  .replace('$#$', '.');
                setJobCloseForm({ ...jobcloseForm, hours: newVal });
              }}
              extra={<Text>小时</Text>}
            />
          </Flex.Item>
        </Flex>
        {jobTask && jobTask.workOrder.substring(0, 3) === 'MCO' && (
          <List>
            <InputItem
              value={jobcloseForm.inspector}
              style={styles.departInput}
              onChange={(val) => {
                setJobCloseForm({ ...jobcloseForm, inspector: val });
              }}
            >
              检查者
            </InputItem>
            <InputItem
              value={jobcloseForm.taskFeedback}
              style={styles.departInput}
              onChange={(val) => {
                setJobCloseForm({ ...jobcloseForm, taskFeedback: val });
              }}
            >
              工作内容反馈
            </InputItem>
            <InputItem
              value={jobcloseForm.flbNo}
              style={styles.departInput}
              onChange={(val) => {
                setJobCloseForm({ ...jobcloseForm, flbNo: val });
              }}
            >
              FLB编号
            </InputItem>
            <InputItem editable={false} value={userStore.user.Name}>
              完工签署
            </InputItem>
          </List>
        )}
        <InputItem
          value={jobcloseForm.depart}
          style={styles.departInput}
          onChange={(val) => {
            setJobCloseForm({ ...jobcloseForm, depart: val });
          }}
        >
          施工单位
        </InputItem>
        <InputItem
          editable={false}
          value={formatDate(
            jobTask && jobTask.finishDate,
            'YYYY/MM/DD HH:mm:ss',
          )}
        >
          完工时间
        </InputItem>
        {jobTask && jobTask.orderType === 'MCO_C' && (
          <RadioButtonGroup
            value={filterOpt}
            options={[
              {
                value: '1',
                text: '已排除故障，关闭保留故障(DD)/保留缺陷(FC)',
              },
              {
                value: '2',
                text: '未排除故障，继续保留该故障/缺陷',
              },
            ]}
            onChange={(val) => setFilterOpt(val)}
          />
        )}
        {jobTask && jobTask.orderType === 'MCO_P' && (
          <RadioButtonGroup
            value={filterOpt}
            options={[
              {
                value: '1',
                text: '已排除故障，关闭停场缺件清单',
              },
              {
                value: '2',
                text: '未排除故障，不关闭停场缺件清单',
              },
            ]}
            onChange={(val) => setFilterOpt(val)}
          />
        )}
        {!fromSign && (
          <List.Item
            extra={
              <PhotoCameraPicker
                onFileChange={(file) =>
                  setJobCloseForm({
                    ...jobcloseForm,
                    filePath: JSON.parse(file).FilePath,
                  })
                }
              />
            }
          >
            上传图片
          </List.Item>
        )}
      </List>
    </Modal>
  );
}

export default forwardRef(MaintainJobClose);
